#include "Classes.h"

Boomerang::Boomerang(Character* pCharacter) {
	Owner = pCharacter;
	posInitial = position2d<s32>(Owner->GetUseItemPosition(this).X,Owner->GetUseItemPosition(this).Y);
	speed = 2.5;
	direction = f32(Owner->GetDirection());
	distance = 600;
	posCurrent = posInitial;
	returning = false;
	// wooden boomerang
	//for (u32 i=0; i< Zelda->BoomerangWoodenImages.size(); i++) {
	//	ImageRects.push_back(&Zelda->BoomerangWoodenImages[i]);
	//}
	// metal boomerang
	for (u32 i=0; i< Zelda->BoomerangMetalImages.size(); i++) {
		ImageRects.push_back(&Zelda->BoomerangMetalImages[i]);
	}
	ImageIterator = 0;
	AnimationInterval = 200/speed;
	LastTimeCheck = Zelda->Device->getTimer()->getTime();
	Colour = Colour::White;
	X = posCurrent.X;
	Y = posCurrent.Y;
	Zelda->Objects.push_back(this);
	Owner->AddItem(this);
}
Boomerang::~Boomerang() {

}
void Boomerang::Act() {
	if(!returning) {
		f32 dX = cos((f32) direction/180*cPi)*speed*Zelda->Scale;
		f32 dY = -sin((f32) direction/180*cPi)*speed*Zelda->Scale;
		if(abs(dX) < cEpsilon)
			dX = 0;
		if(abs(dY) < cEpsilon)
			dY = 0;
		X += s32(dX);
		Y += s32(dY);
		if(posCurrent.getDistanceFrom(posInitial) > distance) {
			returning = true;
		}
	}
	else {
		position2d<s32> target = position2d<s32>(Owner->getX() + Owner->GetImageRect()->getWidth()/2 * Zelda->Scale,Owner->getY() + Owner->GetImageRect()->getHeight()/2 * Zelda->Scale);
		
		f32 rise = f32(target.Y - Y);
		f32 run = f32(target.X - X);
		f32 displacement = f32(target.getDistanceFrom(posCurrent));
		
		if(displacement > 10*Zelda->Scale) {
			X += s32(run/displacement*speed*Zelda->Scale);
			Y += s32(rise/displacement*speed*Zelda->Scale);
		}
		else {
			Owner->UseItem(true);
			if(Owner->GetAction() == ActionUseItem) isActive = false;
		}
	}
	posCurrent.X = X;
	posCurrent.Y = Y;

	if(Zelda->Device->getTimer()->getTime()-LastTimeCheck > AnimationInterval) {
		LastTimeCheck = Zelda->Device->getTimer()->getTime();
		if(ImageIterator < ImageRects.size() - 1) {
			ImageIterator += 1;
		} else {
			ImageIterator = 0;
		}
	}
	if(!Zelda->Sound->isCurrentlyPlaying(Zelda->Sounds[sfxBoomerang]))
		SFX = Zelda->Sound->play2D(Zelda->Sounds[sfxBoomerang],true,false,true);
}
void Boomerang::Draw() {
	s32 width = ImageRects[ImageIterator]->getWidth() * Zelda->Scale;
	s32 height = ImageRects[ImageIterator]->getHeight() * Zelda->Scale;
	Zelda->Driver->draw2DImage(Zelda->SpritesBoomerang,rect<s32>(X-width,Y-height/2,X,Y + width/2),*ImageRects[ImageIterator],0,0,true);
}